package aaa;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Response;
import redis.clients.jedis.resps.Tuple;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RedisMapRepository {
    private final JedisPool jedisPool;
    private static final String CAR_PATH_FORMAT = "car:%s:path";
    private static final String CAR_POSITION_FORMAT = "car:%s:position";

    public RedisMapRepository(String host, int port) {
        this.jedisPool = new JedisPool(host, port);
    }

    public MapData getMapData() {
        try (Jedis jedis = jedisPool.getResource()) {
            Pipeline p = jedis.pipelined();
            Response<String> widthResp = p.get("mapwidth");
            Response<String> heightResp = p.get("mapheight");
            Response<String> obstacleResp = p.get("map:obstacle");
            Response<String> lightResp = p.get("map:light");
            Response<String> carcount = p.get("carcount");
            p.sync();

            int width = Integer.parseInt(widthResp.get());
            int height = Integer.parseInt(heightResp.get());

            int count = 0;
            HashMap<String, Boolean> CarMap = new HashMap<>();
            HashMap<String, Integer> CarId = new HashMap<>();
            if (carcount != null && carcount.get() != null) {
                count = Integer.parseInt(carcount.get());
                for (int i = 1; i <= count; i++) {
                    String pos = getCarPosition(String.valueOf(i));
                    if (pos != null) {
                        CarMap.put(pos, true);
                        CarId.put(pos, i);
                    }
                }
            }

            String obstaclesStr = obstacleResp.get();
            String lightsStr = lightResp.get();

            return new MapData(width, height, obstaclesStr, lightsStr, count, CarMap, CarId);
        } catch (Exception e) {
            System.err.println("Redis读取失败，使用默认地图大小 10x10");
            return new MapData(10, 10, "", "", 0, null, null);
        }
    }

    public String getCarPosition(String carId) {
        try (Jedis jedis = jedisPool.getResource()) {
            Map<String, String> pos = jedis.hgetAll("car:" + carId + ":position");
            if (pos.isEmpty()) {
                return null;
            }
            String x = pos.get("x");
            String y = pos.get("y");
            return x + " " + y;
        } catch (Exception e) {
            return null;
        }
    }

    public List<Tuple> getcarpath(String carId) {
        String key = String.format(CAR_PATH_FORMAT, carId);
        System.out.println("🔍 正在查询 Redis 路径 key: " + key);

        try (Jedis jedis = jedisPool.getResource()) {
            List<Tuple> result = jedis.zrangeWithScores(key, 0, -1);
            if (result == null || result.isEmpty()) {
                System.out.println("⚠️ Redis 返回空结果，请确认 key 是否有数据");
            } else {
                System.out.println("✅ 成功获取路径点数量: " + result.size());
            }
            return result;
        } catch (Exception e) {
            System.err.println("❌ 查询 Redis 路径失败: " + key + ", 错误: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    public static class MapData {
        public final int width;
        public final int height;
        public final String obstaclesStr;
        public final String lightsStr;
        public final int count;
        public final HashMap<String, Boolean> CarMap;
        public final HashMap<String, Integer> CarId;

        public MapData(int width, int height, String obstaclesStr, String lightsStr, int count,
                       HashMap<String, Boolean> car, HashMap<String, Integer> carid) {
            this.width = width;
            this.height = height;
            this.obstaclesStr = obstaclesStr;
            this.lightsStr = lightsStr;
            this.count = count;
            this.CarMap = car;
            this.CarId = carid;
        }
    }

    public int getMapWidth() {
        try (Jedis jedis = jedisPool.getResource()) {
            String width = jedis.get("mapwidth");
            return width == null ? 0 : Integer.parseInt(width);
        } catch (Exception e) {
            return 0;
        }
    }

    public int getMapHeight() {
        try (Jedis jedis = jedisPool.getResource()) {
            String height = jedis.get("mapheight");
            return height == null ? 0 : Integer.parseInt(height);
        } catch (Exception e) {
            return 0;
        }
    }

    public int getCarcount() {
        try (Jedis jedis = jedisPool.getResource()) {
            String count = jedis.get("carcount");
            return count == null ? 0 : Integer.parseInt(count);
        } catch (Exception e) {
            return 0;
        }
    }

    public String getstaticmap() {
        try (Jedis jedis = jedisPool.getResource()) {
            String mapobstacle = jedis.get("map:obstacle");
            if (mapobstacle == null) {
                System.err.println("❌ 障碍物数据为空");
                return null;
            }
            int count = getCarcount();
            int width = getMapWidth();
            StringBuilder obstacleBuilder = new StringBuilder(mapobstacle);

            for (int i = 1; i <= count; i++) {
                Position car = loadCarPosition(String.valueOf(i));
                if (car != null) {
                    int index = car.y * width + car.x;
                    if (index >= 0 && index < obstacleBuilder.length()) {
                        obstacleBuilder.setCharAt(index, '0');
                    } else {
                        System.err.println("⚠️ 小车坐标超出障碍物矩阵范围: " + car);
                    }
                }
            }
            return obstacleBuilder.toString();
        } catch (Exception e) {
            return null;
        }
    }

    private static class Position {
        int x, y;

        Position(int x, int y) {
            this.x = x;
            this.y = y;
        }

        @Override
        public String toString() {
            return x + " " + y;
        }
    }

    private Position loadCarPosition(String carId) {
        try (Jedis jedis = jedisPool.getResource()) {
            String key = String.format(CAR_POSITION_FORMAT, carId);
            String xStr = jedis.hget(key, "x");
            String yStr = jedis.hget(key, "y");

            if (xStr == null || yStr == null) return null;

            try {
                int x = Integer.parseInt(xStr);
                int y = Integer.parseInt(yStr);
                return new Position(x, y);
            } catch (NumberFormatException e) {
                System.out.println("小车位置数据异常");
                return null;
            }
        } catch (Exception e) {
            return null;
        }
    }
    public void cleanMapAndCarData() {
        try (Jedis jedis = jedisPool.getResource()) {
            // 获取小车数量
            int carCount =Integer.parseInt(jedis.get("carcount"));

            // 删除每辆小车相关数据
            for (int carId = 1; carId <= carCount; carId++) {
                jedis.del(
                        "car:" + carId + ":position",
                        "car:" + carId + ":path",
                        "car:" + carId + ":tasks"
                );
            }

            // 删除所有地图相关键
           jedis.del(
                    "map:obstacle",
                    "map:light",
                    "mapwidth",
                    "mapheight",
                    "carcount",
                    "map:alg"
            );

            // 返回删除的总键数 (每辆小车3个键 + 6个固定键)

        } catch (Exception e) {
            System.err.println("❌ 数据清理失败: " + e.getMessage());
        }
    }
}